import threading
import customtkinter as ctk
from tkinter import messagebox
import os
import sys

# 添加项目根目录到系统路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from app import AppController
from .config_tab import ConfigTab
from .orders_tab import OrdersTab
from .log_tab import LogTab
from .order_dialog import OrderDialog
from main import APP_TITLE


class MainWindow(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.title(APP_TITLE)
        self.geometry('1200x800')

        self.controller = AppController()
        self.is_connected = False
        self.current_page = 1
        self.is_refreshing = False
        self._refresh_after_id = None

        self._init_ui()
        self._bind_signals()

    def _init_ui(self):
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.tabs = ctk.CTkTabview(self)
        self.tabs.grid(row=0, column=0, sticky='nsew', padx=10, pady=10)

        env = self.controller.read_env()
        tab_cfg = self.tabs.add('系统配置')
        self.configTab = ConfigTab(tab_cfg, env)

        tab_orders = self.tabs.add('订单管理')
        self.ordersTab = OrdersTab(tab_orders)

        tab_log = self.tabs.add('运行日志')
        self.logTab = LogTab(tab_log)

    def _bind_signals(self):
        self.configTab.on_save = self._on_save_config
        self.configTab.on_connect = self._on_connect

        self.ordersTab.on_refresh = self.refresh_orders
        self.ordersTab.on_prev = self.prev_page
        self.ordersTab.on_next = self.next_page
        self.ordersTab.on_row_activated = self._open_order_dialog

    # ======日志相关======
    def add_log(self, msg: str):
        self.logTab.append(msg)

    # ======配置相关======
    def _on_save_config(self, data: dict):
        self.controller.save_env(data)
        messagebox.showinfo('成功', '配置保存成功', parent=self)
        self.add_log('配置保存成功')

    # ======连接/断开======
    def _on_connect(self, cookie: str):
        if self.is_connected:
            self.is_connected = False
            self.configTab.set_disconnected('已断开')
            self.stop_auto_refresh()
            self.add_log('服务连接已断开')
            return
        if not cookie:
            messagebox.showerror('错误', '请先填写COOKIE')
            return
        self.configTab.set_connecting()
        self.controller.connect_ws(
            cookie=cookie,
            on_connected=self._on_connected,
            on_failed=self._on_connect_failed,
            add_log=self.add_log,
            show_antispam=self._show_antispam_dialog,
        )

    def _on_connected(self):
        self.is_connected = True
        self.configTab.set_connected()
        self.add_log('连接成功')
        if self.ordersTab.auto_refresh_var.get():
            self.start_auto_refresh()

    def _on_connect_failed(self, msg: str):
        self.is_connected = False
        self.configTab.set_disconnected('连接失败')
        self.add_log(f'连接失败: {msg}')
        messagebox.showerror('连接失败', msg)
        self.stop_auto_refresh()

    # ======订单相关======
    def refresh_orders(self):
        if not self.is_connected:
            messagebox.showwarning('警告', '请先连接服务', parent=self)
            return
        if self.is_refreshing:
            self.add_log('正在刷新中，请稍后...')
            return
        self.is_refreshing = True
        self.ordersTab.set_refreshing(True)
        self.ordersTab.set_page_text('加载中...')

        def run():
            try:
                result = self.controller.list_orders(self.current_page, page_size=30)
                if result and result.get('code') == 200:
                    orders = result.get('data', {}).get('list', [])
                    self.after(0, lambda: self._update_orders_ui(orders))
                else:
                    msg = result.get('msg', '获取订单失败') if result else '网络错误'
                    self.after(0, lambda: self._orders_error_ui(msg))
            except Exception as e:
                self.after(0, lambda: self._orders_error_ui(str(e)))
            finally:
                self.is_refreshing = False

        threading.Thread(target=run, daemon=True).start()

    def _update_orders_ui(self, orders):
        self.ordersTab.update_orders(orders)
        self.ordersTab.set_page_text(f'第 {self.current_page} 页 (共{len(orders)}条)')
        self.ordersTab.set_refreshing(False)

    def _orders_error_ui(self, msg: str):
        messagebox.showerror('错误', f'获取订单失败: {msg}', parent=self)
        self.ordersTab.set_page_text(f'第 {self.current_page} 页')
        self.ordersTab.set_refreshing(False)

    def prev_page(self):
        if self.current_page > 1:
            self.current_page -= 1
            self.refresh_orders()

    def next_page(self):
        self.current_page += 1
        self.refresh_orders()

    def _open_order_dialog(self, order: dict):
        dlg = OrderDialog(self, order, self.controller)
        dlg.show()

    # ======自动刷新======
    def start_auto_refresh(self):
        self.stop_auto_refresh()
        self._refresh_after_id = self.after(self.ordersTab.ORDER_REFRESH_INTERVAL * 1000, self._auto_refresh_callback)

    def stop_auto_refresh(self):
        if self._refresh_after_id is not None:
            try:
                self.after_cancel(self._refresh_after_id)
            except Exception:
                pass
            self._refresh_after_id = None

    def _auto_refresh_callback(self):
        if self.ordersTab.auto_refresh_var.get() and self.is_connected and not self.is_refreshing:
            self.refresh_orders()
            self.start_auto_refresh()
        else:
            self.stop_auto_refresh()

    def stop_auto_refresh_and_close(self):
        self.stop_auto_refresh()
        try:
            if hasattr(self, 'configTab') and hasattr(self.configTab, 'shutdown'):
                self.configTab.shutdown()
        except Exception:
            pass
        self.destroy()

    # ======反爬虫弹窗======
    def _show_antispam_dialog(self):
        dlg = ctk.CTkToplevel(self)
        dlg.title('温馨提示')
        dlg.geometry('360x160')
        try:
            dlg.resizable(False, False)
        except Exception:
            pass
        frm = ctk.CTkFrame(dlg)
        frm.pack(fill='both', expand=True, padx=20, pady=20)
        lab = ctk.CTkLabel(frm, text='请刷新闲鱼Cookie\n点击确定断开连接', anchor='center')
        lab.pack(pady=6, fill='both', expand=True)
        btn = ctk.CTkButton(frm, text='确定')
        def on_ok():
            self.add_log('用户确认，已断开连接')
            self._on_connect('')
            try:
                dlg.destroy()
            except Exception:
                pass
        btn.configure(command=on_ok)
        btn.pack(side='bottom', pady=10)
        try:
            dlg.transient(self)
            dlg.attributes('-topmost', True)
            dlg.update_idletasks()
            pw = self.winfo_width()
            ph = self.winfo_height()
            px = self.winfo_rootx()
            py = self.winfo_rooty()
            sw = dlg.winfo_width()
            sh = dlg.winfo_height()
            x = px + (pw - sw) // 2
            y = py + (ph - sh) // 2
            dlg.geometry(f"{sw}x{sh}+{x}+{y}")
            dlg.focus()
        except Exception:
            pass

